import base from "./base.controller";
import md5 from "md5";

export default class extends base {

    async _initialize() {
        await super._initialize();
    }

    async index() {

        // let item= await this.C('LIST_ROWS');
        // this.logger.debug(item);
        // await this.C('LIST_ROWS',10);
        // item= await this.C('LIST_ROWS');
        // this.logger.debug(item);


        let Model = this.model('admin/Config');
        //'CONFIG_GROUP_LIST'
        let data = await Model.findOne({key: `CONFIG_GROUP_LIST`}).exec();
        let groups = [];
        for (let item of data['value'].split('|')) {
            let pairs = item.split(':');
            groups.push({key: Number(pairs[0]), title: pairs[1]});
        }

        await this.render('admin/config/index', {
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}],
            groups: groups
        });
    }

    async table() {
        const p = this.query.page || 1;

        const post = this.post;
        const id = post.id.trim();
        const status = post.status.trim();
        const keywords = post.keywords.trim();
        const group = post.group.trim();

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {key: {$regex: keywords, $options: "$i"}},
                    {title: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (status !== "") {
            queryParams = Object.assign(queryParams, {status: status});
        }

        if (group !== "") {
            queryParams = Object.assign(queryParams, {group: Number(group)});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: koahub.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error('没找到符合条件的记录');
                return;
            }
        }
        this.logger.debug(`search queryParams:${JSON.stringify(queryParams)}`);

        const pageSize= await this.common.config('LIST_ROWS');
        const pageEntity = await this.model('admin/Config').findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {group:'desc',updatedAt: 'desc'}, function (error, results) {
            // console.log(results);
        });

        await this.render('admin/config/table', {
            records: pageEntity.data,
            pager: this.common.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
    }

    async disable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        const Model = this.model('admin/Config');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('禁用用户成功');
    }

    async enable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Config');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            // this.changeModelField('admin/Config', i, 'status', 1);
        }
        this.success('开启用户成功');
    }

    async delete() {
        const id = this.post.id || "";
        const ids = id.split(',');
        const Model = this.model('admin/Config');
        for (const i of ids) {
            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/admin/index', '删除用户成功');
    }

    async add() {

        if (this.isPost()) {

            const config = this.post;

            if (config.key) {

            } else {
                this.error('参数错误')
            }

            if (config.id === "") {
                delete config.id;
            }

            this.model('admin/Config').saveOrUpdate(config);

            this.success('/admin/config/index', '保存成功');

        } else {
            //Edit
            const Model = this.model('admin/Config');
            const data = await Model.findOne({key: `CONFIG_GROUP_LIST`}).exec();
            let groups = [];
            for (const item of data['value'].split('|')) {
                const pairs = item.split(':');
                groups.push({key: Number(pairs[0]), title: pairs[1]});
            }

            const valueTypes = [
                {key: 'Number', title: '数字'},
                {key: 'String', title: '字符串'},
                {key: 'Text', title: '文本'},
                {key: 'Array', title: '数组'},
                {key: 'MultiCheckList', title: '多选框'}
            ];

            const options = {
                groups: groups,
                valueTypes: valueTypes
            };

            if (this.query.id) {
                const config = await Model.findOne({_id: this.query.id}).exec();
                await this.render('admin/config/add', Object.assign(options, {config: config}));
            } else {
                //add new item
                await this.render('admin/config/add', options);
            }
        }
    }
}